package com.mengniu.commerce.sync.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mengniu.commerce.common.core.domain.R;
import com.mengniu.commerce.common.core.enums.ModuleEnum;
import com.mengniu.commerce.common.core.enums.SourceEnum;
import com.mengniu.commerce.common.core.utils.IdGeneratorSnowflake;
import com.mengniu.commerce.common.template.enums.APIUrlEnum;
import com.mengniu.commerce.sync.api.base.CreateItemResult;
import com.mengniu.commerce.sync.api.base.MnResult;
import com.mengniu.commerce.sync.api.domain.BaseMnItemModel;
import com.mengniu.commerce.sync.api.domain.CreateItemModel;
import com.mengniu.commerce.sync.api.domain.ModifyItemModel;
import com.mengniu.commerce.sync.api.dto.RetryDTO;
import com.mengniu.commerce.sync.common.constant.CodeConstants;
import com.mengniu.commerce.sync.common.utils.MnResultUtil;
import com.mengniu.commerce.sync.common.utils.RestTemplateUtil;
import com.mengniu.commerce.sync.exception.RetryException;
import com.mengniu.commerce.sync.mapper.MnItemMapper;
import com.mengniu.commerce.sync.model.MnItemModel;
import com.mengniu.commerce.sync.service.ItemService;
import com.mengniu.commerce.sync.utils.RetryUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.RetryContext;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.support.RetrySynchronizationManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 商品相关实现类
 */
@Service
@Slf4j
public class ItemServiceImpl implements ItemService {

    public static final String baseURL = "https://t-openapi-gateway.mengniu.cn/";
    @Resource
    private RestTemplateUtil restTemplateUtil;

    @Resource
    private MnItemMapper mnItemMapper;

    @Resource
    private RetryUtils retryUtils;

    /**
     *创建蒙牛商品
     */
    @Override
    @Retryable(value = { RetryException.class }, maxAttempts = 8, backoff = @Backoff(delay = 10000))
    public R createItem(List<CreateItemModel> createItemModelList,RetryDTO retryDTO) {
        log.info("创建蒙牛商品入参{}", JSONObject.toJSONString(createItemModelList));
        JSONObject param = new JSONObject();
        param.put("itemCreateList",createItemModelList);
        param.put("creatorId","蒙牛中间件");
        param.put("fromSys","APP_DSZJJ");
        JSONObject data = new JSONObject();
        RetryContext context = RetrySynchronizationManager.getContext();
        log.info("当前创建蒙牛商品重试次数{}",JSONObject.toJSONString(context));
        try {
            data = restTemplateUtil.doPost(param, baseURL + APIUrlEnum.CREATE_ITEM.getPath());
            log.info("调用创建蒙牛商品响应为{}",JSONObject.toJSONString(data));
        }catch (Exception e){
            log.error("调用创建蒙牛商品接口失败",e);
            Long id = retryUtils.insertOrUpdate(param, retryDTO.getSource(), retryDTO.getStoreName(), ModuleEnum.ITEM.getModuleName(), APIUrlEnum.CREATE_ITEM.getMethod(), context.getRetryCount(), e.getMessage(),retryDTO.getRetryId());
            retryDTO.setRetryId(id);
            throw new RetryException("发生了重试异常{}", e);
        }
        CreateItemResult createItemResult = JSONObject.parseObject(data.toJSONString(), CreateItemResult.class);
        List<CreateItemResult.Item> result = createItemResult.getResult();
        List<MnItemModel> mnItemModels = new ArrayList<>();
        for (int i = 0; i < result.size(); i++) {
            CreateItemResult.Item item = result.get(i);
            CreateItemModel createItemModel = createItemModelList.get(i);
            if (item.getSuccess()){
                String mnItemId = item.getItemId().get(0);
                MnItemModel createMnItemModel = this.createMnItemModel(createItemModel,mnItemId);
                mnItemModels.add(createMnItemModel);
            }else {
                log.warn("蒙牛商品创建失败，失败商品是{}_失败原因是{}",JSONObject.toJSONString(createItemModel),item.getMessage());
            }
        }
        log.info("落库时商品数据为{}",JSONObject.toJSONString(mnItemModels));
        mnItemMapper.insertBatch(mnItemModels);
        return R.ok(MnResultUtil.resultSuccess(result));
    }


    /**
     *修改蒙牛商品
     */
    @Override
    @Retryable(value = { RetryException.class }, maxAttempts = 8, backoff = @Backoff(delay = 10000))
    public R modifyItem(ModifyItemModel modifyItemModel,RetryDTO retryDTO) {
        log.info("修改蒙牛商品入参{}", JSONObject.toJSONString(modifyItemModel));
        JSONObject param = (JSONObject) JSON.toJSON(modifyItemModel);
        log.info("修改蒙牛商品参数为{}",JSONObject.toJSONString(param));
        JSONObject result = new JSONObject();
        RetryContext context = RetrySynchronizationManager.getContext();
        log.info("当前修改蒙牛商品重试次数{}",JSONObject.toJSONString(context));
        try{
            result = restTemplateUtil.doPost(param, baseURL + APIUrlEnum.MODIFY_ITEM.getPath());
            log.info("调用修改蒙牛商品响应为{}",JSONObject.toJSONString(result));
        }catch (Exception e){
            log.error("调用修改蒙牛商品接口失败",e);
            Long id = retryUtils.insertOrUpdate(param, retryDTO.getSource(), retryDTO.getStoreName(), ModuleEnum.ITEM.getModuleName(), APIUrlEnum.MODIFY_ITEM.getMethod(), context.getRetryCount(), e.getMessage(),retryDTO.getRetryId());
            retryDTO.setRetryId(id);
            throw new RetryException("发生了重试异常{}", e);
        }
        if (result == null || ! result.getInteger("code").equals(CodeConstants.SUCCESS_CODE)){
            return R.fail(result,"调用蒙牛接口失败");
        }
        MnItemModel updateMnItemModel = this.updateMnItemModel(modifyItemModel);
        mnItemMapper.updateMnItem(updateMnItemModel);
        return R.ok(result);
    }

    private MnItemModel updateMnItemModel(ModifyItemModel modifyItemModel) {
        MnItemModel mnItemModel = mnItemMapper.selectMnItem(modifyItemModel.getItemId(),null,null);
        mnItemModel.setLeafCategoryId(modifyItemModel.getLeafCategoryId());
        mnItemModel.setItemDescription(modifyItemModel.getDescription());
        mnItemModel.setSubDescription(modifyItemModel.getSubdescription());
        mnItemModel.setMemo(modifyItemModel.getMemo());
        mnItemModel.setItemType(modifyItemModel.getItemType());
        mnItemModel.setSalePoints1(modifyItemModel.getSalePoints1());
        mnItemModel.setSalePoints2(modifyItemModel.getSalePoints2());
        mnItemModel.setSalePoints3(modifyItemModel.getSalePoints3());
        mnItemModel.setDescription(modifyItemModel.getDescription());
        mnItemModel.setSelfSupportType(modifyItemModel.getSelfSupportType());
        mnItemModel.setAllowSearch(modifyItemModel.getAllowSearch());
        mnItemModel.setAllowBooking(modifyItemModel.getAllowBooking());
        mnItemModel.setSaleRange(modifyItemModel.getSaleRange());
        mnItemModel.setPayType(modifyItemModel.getPayType());
        mnItemModel.setNewExclusive(modifyItemModel.getNewExclusive());
        mnItemModel.setAllowAfterSale(modifyItemModel.getAllowAfterSale());
        mnItemModel.setReturnPolicy(modifyItemModel.getReturnPolicy());
        mnItemModel.setFromSys(modifyItemModel.getFromSys());
        mnItemModel.setImageList(JSONObject.toJSONString(modifyItemModel.getImageList()));
        mnItemModel.setVideoList(JSONObject.toJSONString(modifyItemModel.getVideoList()));
        mnItemModel.setItemPropertyValueList(JSONObject.toJSONString(modifyItemModel.getItemPropertyValueList()));
        mnItemModel.setSupportDeliveryType(modifyItemModel.getSupportDeliveryType() + "");
        mnItemModel.setSaleRule(modifyItemModel.getSaleRule() + "");
        mnItemModel.setStoreConfig(JSONObject.toJSONString(modifyItemModel.getStoreConfig()));
        mnItemModel.setSkuList(JSONObject.toJSONString(modifyItemModel.getSkuList()));
        mnItemModel.setModifier(modifyItemModel.getModifier());
        mnItemModel.setUpdateTime(new Date());
        return mnItemModel;
    }


    public MnItemModel createMnItemModel(CreateItemModel createItemModel, String mnItemId) {
        MnItemModel mnItemModel = new MnItemModel();
        mnItemModel.setId(new IdGeneratorSnowflake().snowflakeId());
        mnItemModel.setMnItemId(mnItemId);
        if (createItemModel.getSource().equals(SourceEnum.YZ.getSource())){
            mnItemModel.setYzItemId(createItemModel.getItemId());
        }
        if (createItemModel.getSource().equals(SourceEnum.WM.getSource())){
            mnItemModel.setWmItemId(createItemModel.getItemId());
        }
        mnItemModel.setLeafCategoryId(createItemModel.getLeafCategoryId());
        mnItemModel.setItemDescription(createItemModel.getDescription());
        mnItemModel.setSubDescription(createItemModel.getSubdescription());
        mnItemModel.setMemo(createItemModel.getMemo());
        mnItemModel.setItemType(createItemModel.getItemType());
        mnItemModel.setSalePoints1(createItemModel.getSalePoints1());
        mnItemModel.setSalePoints2(createItemModel.getSalePoints2());
        mnItemModel.setSalePoints3(createItemModel.getSalePoints3());
        mnItemModel.setDescription(createItemModel.getDescription());
        mnItemModel.setSelfSupportType(createItemModel.getSelfSupportType());
        mnItemModel.setAllowSearch(createItemModel.getAllowSearch());
        mnItemModel.setAllowBooking(createItemModel.getAllowBooking());
        mnItemModel.setSaleRange(createItemModel.getSaleRange());
        mnItemModel.setPayType(createItemModel.getPayType());
        mnItemModel.setNewExclusive(createItemModel.getNewExclusive());
        mnItemModel.setAllowAfterSale(createItemModel.getAllowAfterSale());
        mnItemModel.setReturnPolicy(createItemModel.getReturnPolicy());
        mnItemModel.setFromSys(createItemModel.getFromSys());
        mnItemModel.setMainKu(createItemModel.getCreatorId());
        mnItemModel.setImageList(JSONObject.toJSONString(createItemModel.getImageList()));
        mnItemModel.setVideoList(JSONObject.toJSONString(createItemModel.getVideoList()));
        mnItemModel.setItemPropertyValueList(JSONObject.toJSONString(createItemModel.getItemPropertyValueList()));
        mnItemModel.setSupportDeliveryType(createItemModel.getSupportDeliveryType() + "");
        mnItemModel.setSaleRule(createItemModel.getSaleRule() + "");
        mnItemModel.setStoreConfig(JSONObject.toJSONString(createItemModel.getStoreConfig()));
        mnItemModel.setSkuList(JSONObject.toJSONString(createItemModel.getSkuList()));
        mnItemModel.setCreateTime(new Date());
        return mnItemModel;
    }


    public static void main(String[] args) {
        List<BaseMnItemModel.Image> imageList = new ArrayList<>();
        BaseMnItemModel.Image image = new BaseMnItemModel.Image();
        image.setMajor("true");
        image.setPosition(1);
        image.setUrl("https://image-c.weimobwmc.com/ol-6NoGC/d82939845c5c451796a90845859974f1.jpg");
        BaseMnItemModel.Image image2 = new BaseMnItemModel.Image();
        image2.setMajor("true");
        image2.setPosition(1);
        image2.setUrl("https://image-c.weimobwmc.com/ol-6NoGC/d82939845c5c451796a90845859974f1.jpg");
        BaseMnItemModel.Image image3 = new BaseMnItemModel.Image();
        image3.setMajor("true");
        image3.setPosition(1);
        image3.setUrl("https://image-c.weimobwmc.com/ol-6NoGC/d82939845c5c451796a90845859974f1.jpg");
        BaseMnItemModel.Image image4 = new BaseMnItemModel.Image();
        image4.setMajor("true");
        image4.setPosition(1);
        image4.setUrl("https://image-c.weimobwmc.com/ol-6NoGC/d82939845c5c451796a90845859974f1.jpg");
        imageList.add(image);
        imageList.add(image2);
        imageList.add(image3);
        imageList.add(image4);
        System.out.println(JSONObject.toJSONString(imageList));

    }



}
